package com.example.suze.libraryinformationmanagementsystem.Activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.suze.libraryinformationmanagementsystem.R;
import com.example.suze.libraryinformationmanagementsystem.net.API;
import com.example.suze.libraryinformationmanagementsystem.net.JSONCallBack;
import com.example.suze.libraryinformationmanagementsystem.net.entiry.ReturnStateEntity;
import com.person.CommonUtils;
import com.person.dao.BookDao;
import com.person.dao.DBManager;
import com.person.dao.DaoSession;
import com.person.entity.Book;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by suze on 2017/6/12.
 */

public class AddActivity extends BaseActivity implements View.OnClickListener{
    private Button add,sure;
    private ImageView imageView;
    private Intent intent = new Intent();
    private String path;
    private static final int CHOOSE_FILE = 998;//选择作业的请求码
    private EditText name,author,publishing,tag,id,abstract1;
    private String name1,author1,publishing1,abstract2;
    private String tag1;
    private long id1;
    private JSONCallBack callBack;
    API api = API.getAPI(AddActivity.this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        findView();
    }
    private void findView(){
        add= (Button) findViewById(R.id.img_book1);
        sure= (Button) findViewById(R.id.add_sure1);
        imageView = (ImageView) findViewById(R.id.img_book_show);
        name = (EditText) findViewById(R.id.name_book1);
        author = (EditText) findViewById(R.id.author_book1);
        publishing = (EditText) findViewById(R.id.publishing_book1);
        tag = (EditText) findViewById(R.id.tag_book1);
        id = (EditText) findViewById(R.id.id_book1);
        abstract1=(EditText) findViewById(R.id.abstract_book1);
        add.setOnClickListener(this);
        sure.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.add_sure1:
                name1 = name.getText().toString();
                author1 = author.getText().toString();
                publishing1 = publishing.getText().toString();
                abstract2 = abstract1.getText().toString();
                tag1 = tag.getText().toString();
                id1 = Long.parseLong(id.getText().toString());
//                Book book = new Book();
//                book.setName(name1);
//                book.setAuthor(author1);
//                book.setPublishing(publishing1);
//                book.setTag(tag1);
//                book.setId(id1);
//                book.setImg(path);
//                book.setAbstract1(abstract2);
//                book.setBorrowerId(1l);
//                book.setTimeOut("");
//                book.setTimeIn("");
//                CommonUtils commonUtils = new CommonUtils(this);
//                commonUtils.insertFriend(book);
                callBack = new JSONCallBack<ReturnStateEntity>(new ReturnStateEntity()) {
                    @Override
                    public void onSuccess(ReturnStateEntity entity) {
                        Log.v("login", entity.getState()+" "+entity.getCode());
                        if(entity.getState().equals("success") && entity.getCode() == 0){
                            Looper.prepare();
                            Toast.makeText(AddActivity.this, "新增图书成功", Toast.LENGTH_LONG).show();
                            Looper.loop();
                            finish();
                        }else{
                            Looper.prepare();
                            Toast.makeText(AddActivity.this, "新增图书失败", Toast.LENGTH_LONG).show();
                            Looper.loop();
                        }
                    }
                };
                api.sqlOporate("insert", "INSERT INTO book ( No, book_name ,is_lend ,tag ,author ,publishing ,abstract1,img )VALUES( "+"'"+id1+"'"+","+"'"+name1+"'"+","+"0"+","+"'"+tag1+"'"+","+"'"+author1+"'"+","+"'"+publishing1+"'"+","+"'"+abstract2+"'"+","+"'"+path+"'"+");", callBack);
                break;
            case R.id.img_book1:
                chooseFile();
                break;
        }
    }
    /**
     * 选择本地文件
     **/
    private void chooseFile() {
        intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
                    CHOOSE_FILE);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /**
     * 选择附件后返回操作
     *
     * @param requestCode 请求码
     * @param resultCode  返回码
     * @param data        返回带回来的数据
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == CHOOSE_FILE && resultCode == RESULT_OK) {
            if (data != null) {
                imageView.setImageURI(data.getData());
                Bitmap image = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
                path = bitmapToBase64(image);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
